// 运行时配置
import { Toast } from 'antd-mobile';
import type { RequestConfig } from 'umi';

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
let isLoading = false;

export const request: RequestConfig = {
  timeout: 1000,
  // other axios options you want
  errorConfig: {
    errorHandler() { },
    errorThrower() { },
  },
  requestInterceptors: [
    (url, options) => {
      options.headers['x-csrf-token'] =
        document.cookie && document.cookie.split('=')[1];
      isLoading = true;
      if (isLoading) {
        Toast.show({
          icon: 'loading',
          content: '加载中…',
          duration: 0,
        });
      }
      // do something
      return { url, options };
    },
  ],
  responseInterceptors: [
    (response) => {
      const { data } = response;
      const whiteList = ['/api/v1/queryUserList'];
      let flag = whiteList.some((item) => item === response.config.url);
      isLoading = false;
      if (!isLoading) {
        Toast.clear();
      }
      if (!flag && data && data.code !== 1) {
        return Promise.reject(data);
      }
      return response;
    },
  ],
};
